package com.qianfeng.gl4study.youshare.tasks;

import android.os.AsyncTask;
import com.qianfeng.gl4study.youshare.utils.HttpTool;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * I'm glad to share my knowledge with you all.
 * User:Gaolei
 * Date:2015/2/5
 * Email:pdsfgl@live.com
 */
public class LoginTask extends AsyncTask<String,Integer,JSONObject> {

	//用于调用实际接收数据的对象，可以认为是Activity/Fragment.来进行UI的更新
	private TaskProcessor processor;

	public LoginTask(TaskProcessor processor){
		this.processor = processor;
	}

	@Override
	protected JSONObject doInBackground(String... params) {

		JSONObject ret = null;
		if(params!=null&&params.length>=2){
			String userName = params[0];
			String userPassword = params[1];

			HashMap<String, String> map = new HashMap<String, String>();
			map.put("user",userName);
			map.put("password",userPassword);
			String url = "http://open.doushangshang.com/user.php?ac=login";
			byte[] bytes = HttpTool.post(url, map);
			if(bytes!=null) {
				try {
					String str = new String(bytes, "UTF-8");
					ret = new JSONObject(str);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		return ret;
	}

	@Override
	protected void onPostExecute(JSONObject jsonObject) {
		if(processor!=null){
			processor.processResult(jsonObject,3);
		}
	}
}
